<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import { ReloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

import { getFreightIdList, getSendGoodsInfo, updateSendGoodsInfo } from '#/api';
import { auto1688stor } from '#/store';
import { formatMoney, formatMoneyToCent } from '#/utils';

const route = useRoute();
const { shopId } = route.query;

type FormStateType = {
  sendOrderTime: number;
  tbId: number | string;
};

const formState: any = reactive<FormStateType>({
  tbId: '',
  sendOrderTime: 0,
});
const dynalightIdList = ref([]);
const loadingGetling = ref(false);
const loadingFetMaxAlls = ref(false);
const auto1688storTres = auto1688stor();
const nowData = computed(() => auto1688storTres.auto1688.nowSelectDyShop);
const dataInxiayou = auto1688storTres.auto1688.bindShopList?.filter(
  (item) => item.pType === 2,
);
onMounted(() => {
  initPageData();
});
function initPageData() {
  if (!nowData.value) return;
  getSendGoodsInfoFunc();
  getFreight();
}
const selectNow = ref(shopId || nowData.value?.shopId);
watch(nowData, (newQuestion, oldQuestion) => {
  if (newQuestion.shopId !== oldQuestion.shopId) {
    // 刷新页面数据
    selectNow.value = newQuestion.shopId;
    initPageData();
  }
});
// 获取店铺的基础设置
function getSendGoodsInfoFunc() {
  if (!nowData.value) return;
  loadingFetMaxAlls.value = true;
  getSendGoodsInfo({ shopId: selectNow.value }).then((res) => {
    Object.keys(res).forEach((key: string) => {
      formState[key] = res[key] as FormStateType;
    });
    formState.addPricePercentage =
      formatMoneyToCent(res.addPricePercentage) || 100;
    loadingFetMaxAlls.value = false;
  });
}

// 获取运费模版
function getFreight() {
  loadingGetling.value = true;

  if (!nowData.value) return;
  getFreightIdList({ shopId: selectNow.value }).then((res) => {
    loadingGetling.value = false;
    dynalightIdList.value = res.list.map((item: any) => item.template);
  });
}
function jumpAddYunfei() {
  open('https://fxg.jinritemai.com/ffa/morder/logistics/freight-list');
}
const fieldNames = {
  label: 'templateName',
  value: 'id',
};
const labelCol = { style: { width: '150px' } };
const buyLink = import.meta.env.VITE_APP_BUY_DOUDIAN_LINK;
function toBuyDYApp() {
  open(buyLink);
}

function saveShopConfig() {
  const saveDataInfo = {
    shopId: selectNow.value,
    sendOrderTime: formState.sendOrderTime,
  };
  loadingFetMaxAlls.value = true;
  updateSendGoodsInfo(saveDataInfo).then(() => {
    // console.log('保存店铺设置', res);
    message.success('保存成功');
    loadingFetMaxAlls.value = false;
    getSendGoodsInfoFunc();
  });
}
</script>

<template>
  <div v-if="nowData && nowData.shopId" class="px-4 py-4">
    <a-spin :spinning="loadingFetMaxAlls">
      <a-form :label-col="labelCol" :model="formState" layout="inline">
        <a-space direction="vertical">
          <dly-tip-box class="mt-4" title="选择店铺">
            <a-space class="ml-12" direction="vertical">
              <a-form-item label="选择店铺">
                <!-- <a-space>
                <span>代发价X</span> -->
                <a-select
                  v-model:value="selectNow"
                  :field-names="{
                    label: 'shopName',
                    value: 'shopId',
                  }"
                  :options="dataInxiayou"
                  style="width: 200px"
                  @change="initPageData"
                />
                <!-- </a-space> -->
              </a-form-item>
            </a-space>
          </dly-tip-box>
          
          <!-- </a-space>
      <a-space direction="vertical"> -->
      
          <dly-tip-box class="mt-4" title="下单时机">
            <a-form-item label="用户下单">
              <!-- <a-space>
                <span>代发价X</span> -->
              <a-space>
                <a-input-number
                  v-model:value="formState.sendOrderTime"
                  :min="0"
                  addon-after="分钟后下单"
                />
              </a-space>

              <!-- </a-space> -->
            </a-form-item>
          </dly-tip-box>
          <a-form-item>
            <a-button
              class="ml-28 mt-24"
              type="primary"
              @click="saveShopConfig"
            >
              保存
            </a-button>
          </a-form-item>
        </a-space>
      </a-form>
    </a-spin>
  </div>
  <div v-else class="px-4 py-4">
    暂未绑定店铺：<a-button type="primary" @click="toBuyDYApp">
      前往绑定
    </a-button>
  </div>
</template>
